import _ from 'lodash';

class LoaderProxy {
  constructor(controller, conditions) {
    // 定义的接口数据的2种类型：list和form
    let apis = [];
    
    apis.push(...this.fillUrls(controller.urls.model, 'form'));
    apis.push(...this.fillUrls(controller.urls.query, 'list'));

    let querys = []; // 请求promise
    // 追加参数，controller.$params表示url的?后面的查询参数
    let params = _.extend({}, controller.$params, conditions || {});

    _.each(apis, (api, idx) => {
      // 借助于loader.js来发请求
      let loader = new controller.$framework.Loader(controller, api);
      let waiting = loader.query(params);
      if (controller.$util.isPromise(waiting)) {
        let p = new Promise((rs, rj) => {
          waiting.then((v) => {
            rs(v);
          }, (v) => {
            rj(v);
          });
        });
        querys.push(p);
      }
      // 设置进controller的loaders数组里
      controller.setLoader(loader);
    });

    this.querys = querys;
    this.controller = controller;
  }

  /**
   * 填充url，最终的对象为：{ url: '', method: 'post', type: '', index: 1, priority: 1 }
   */
  fillUrls(target, prefix) {
    let urls = []
    if (!target) {
      return urls
    } 
    if (_.isString(target)) {
      // 字符串
      urls.push({ url: target, method: 'post', type: prefix, index: '', priority: 1 })
    } else if (_.isArray(target)) {
      // 数组
      target.forEach((item, idx) => {
        if (_.isString(item)) {
          urls.push({ url: item, method: 'post', type: prefix, index: idx, priority: 1 })
        } else {
          urls.push(
            _.extend({}, { url: '', method: 'post', priority: 1 }, item, { type: prefix, index: idx })
          )
        }
      })
    } else {
      // json对象
      urls.push(
        _.extend({}, { url: '', method: 'post', priority: 1 }, target, { type: prefix, index: '' })
      )
    } 
    return urls
  }

  load(resolve, reject, preloader = true, isNew = false, context = {}) {
    //初始化页面参数 ------------新增
    if (isNew) {
      _.extend(this.controller.context, context);
    }

    if (this.querys.length == 0) {
      // 无需发起请求，则直接resolve让页面跳转
      this.controller.bind({});
      resolve();
    } else {
      Promise.all(this.querys)
        .then((values) => {
          this.controller.bind(values);
          this.controller.reload = false;
          resolve();
        }, (values) => {
          reject(values || "请求数据失败，请稍后重试");
        })
        .catch(e => {
          console.error(e);
        });
    }
  }
  
}

export default LoaderProxy;
